// 初始化数据
var cmd_movition_ctrl = 1;
var slow_speed = 0.2;
var max_speed = 0.5;
var speed_rate = 1.0;
var lastKeyTime = 0; // 上次按键时间
var keyDebounceDelay = 100; // 防抖延迟(ms)

// 配置 Socket.IO 服务
var socketJson = io('http://' + location.host + '/move');

// 等待连接建立后再发送初始消息
socketJson.on('connect', function() {
    console.log('Socket.IO 连接已建立');
    // 发送初始停止命令
    socketJson.emit('json', {'T':1,'L':0,'R':0});
});

// 监听连接错误
socketJson.on('connect_error', function(error) {
    console.error('Socket.IO 连接错误:', error);
});
//发送控制小车移动指令
function cmdJsonCmd(jsonData){
    console.log('发送控制命令:', jsonData);
    
    // 保存原始值并应用速度系数
    if (jsonData.T == cmd_movition_ctrl) {
        heartbeat_left = jsonData.L;
        heartbeat_right = jsonData.R;
        jsonData.L = heartbeat_left * speed_rate;
        jsonData.R = heartbeat_right * speed_rate;
        console.log('应用速度系数后:', jsonData);
    }
    
    // 发送命令
    socketJson.emit('json', jsonData);
    console.log('命令已通过 Socket.IO 发送');
}

// 每 1 秒刷新数据
setInterval(() => {
    fetch('/data').then(r => r.json()).then(d => {
        document.getElementById('temp').textContent  = d.temperature;
        document.getElementById('speed').textContent = d.speed;
        document.getElementById('time').textContent  = d.time;
    });
}, 1000);

//--------键盘输入wasd控制方向 ----------//
document.onkeydown = (e) => {
    // 防抖处理，避免按键过快触发
    const now = Date.now();
    if (now - lastKeyTime < keyDebounceDelay) return;
    lastKeyTime = now;
    switch (e.key) {
        case 'w':
            cmdJsonCmd({'T':cmd_movition_ctrl,'L':max_speed,'R':max_speed});
            break;
        case 's':
            cmdJsonCmd({'T':cmd_movition_ctrl,'L':-max_speed,'R':-max_speed});
            break;
        case 'a':
            cmdJsonCmd({'T':cmd_movition_ctrl,'L':slow_speed,'R':max_speed});
            break;
        case 'd':
            cmdJsonCmd({'T':cmd_movition_ctrl,'L':max_speed,'R':slow_speed});
            break;
    }
};
document.onkeyup = (e) => {
    const keys = ['w', 's', 'a', 'd'];
    if (keys.includes(e.key)) {
        cmdJsonCmd({'T':cmd_movition_ctrl,'L':0,'R':0});
    }
};
//-----------------------------------//

  // 设备按钮同理
  document.addEventListener('click', e => {
    if (!e.target.classList.contains('device-btn')) return;
    fetch(`/device/${e.target.dataset.dev}/${e.target.dataset.action}`);
  });